package com.hanshg.cherry.controller.log;

import com.hanshg.cherry.base.result.PageTableRequest;
import com.hanshg.cherry.base.result.Results;
import com.hanshg.cherry.model.SysLog;
import com.hanshg.cherry.service.log.LogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日志控制器
 *
 * @author 柠檬水
 * @date 2020/04/13
 */
@Controller
@RequestMapping("log")
@Slf4j
@Api(tags = "日志控制层")
public class LogController {

    private final LogService logService;

    public LogController(LogService logService) {
        this.logService = logService;
    }

    @GetMapping("/list")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:log:query')")
    @ApiOperation(value = "分页获取日志信息", notes = "分页获取日志信息")//描述
    @ApiImplicitParam(name = "page", value = "分页查询实体类")
    public Results<SysLog> getLogs(PageTableRequest page,Integer type,Integer typeMenu) {
        log.info("LogController.getLogs():param (page=" + page + ")");
        page.countOffset();//计算
        return logService.getAllLogByPage(type,typeMenu,page.getOffset(), page.getLimit());
    }

    /**
     * 处理日期转换
     */
    String pattern = "yyyy-MM-dd";

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(pattern), true));
    }

    @GetMapping("/findLogByUsername")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:log:query')")
    @ApiOperation(value = "模糊查询日志信息", notes = "模糊搜索查询日志信息")//描述
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "模糊搜索的用户名", required = true),
    })
    public Results<SysLog> findLogByUsername(PageTableRequest page, String username,Integer type) {
        log.info("LogController.findLogByUsername():param (page=" + page + "+" + username + ")");
        page.countOffset();//计算
        return logService.findLogByUsernameByPage(username,type, page.getOffset(), page.getLimit());
    }
}
